package com.soxing.braindata.web.controller.research;

import com.soxing.braindata.dao.entity.Equipment;
import com.soxing.braindata.dao.entity.TesteeExperiment;
import com.soxing.braindata.domain.vo.EquipmentVo;
import com.soxing.braindata.domain.vo.TesteeVisitExperimentVo;
import com.soxing.braindata.domain.vo.TesteeVo;
import com.soxing.braindata.service.manager.ITesteeExperimentManager;
import com.soxing.braindata.service.manager.ITesteeManager;
import com.soxing.common.utils.response.WebResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.stream.Collectors;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/**
 * @author :durango
 * @date :2022/7/24 20:06
 * @description 被试数据采集控制器
 */
@Slf4j
@RestController
@RequestMapping("/research/data")
@Api(value = "被试数据采集管理", tags = {"被试数据采集管理"})
public class TesteeDataController {
    @Resource
    private ITesteeManager testeeManager;
    @Resource
    private ITesteeExperimentManager testeeExperimentManager;

    /**
     * 通过被试编码获取被试vo
     *
     * @param testeeNo
     * @return
     */
    @GetMapping("/getVoByNo")
    @ApiOperation(value = "通过被试编码获取被试vo")
    public WebResponse<TesteeVo> getVoByNo(@RequestParam String testeeNo) {
        return testeeManager.getVoByNo(testeeNo);
    }

    /**
     * 基于被试编码获取被试访视实验列表
     *
     * @param testeeNo
     * @return
     */
    @GetMapping("/getTesteeVisitExperiment")
    @ApiOperation(value = "基于被试编码获取被试访视实验列表")
    public WebResponse<List<TesteeVisitExperimentVo>> getTesteeVisitExperiment(@RequestParam String testeeNo) {
        return testeeExperimentManager.getTesteeVisitExperiment(testeeNo);
    }

    @PostMapping
    @ApiOperation(value = "新增被试实验数据")
    public WebResponse<Boolean> add(@RequestBody TesteeExperiment testeeExperiment) {
        return testeeExperimentManager.add(testeeExperiment);
    }

    /**
     * 更新被试实验数据
     *
     * @param testeeExperiment
     * @return 返回操作结果 true:成功 false:失败
     */
    @PutMapping
    @ApiOperation(value = "更新被试实验数据")
    public WebResponse<Boolean> update(TesteeExperiment testeeExperiment) {
        if (testeeExperiment.getId() == null) {
            return WebResponse.fail("主键ID为空");
        }
        return testeeExperimentManager.update(testeeExperiment);
    }

    /**
     * 基于id获取被试实验数据信息
     *
     * @param id
     * @return 返回被试实验数据信息
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "基于id获取被试实验数据信息")
    public WebResponse<TesteeExperiment> getById(@PathVariable("id") Integer id) {
        return testeeExperimentManager.getById(id);
    }


    /**
     * 基于id删除被试实验数据记录
     *
     * @param id 主键ID
     * @return 返回操作结果 true:成功 false:失败
     */
    @PostMapping("/delete/{id}")
    @ApiOperation(value = "基于id删除被试实验数据记录")
    public WebResponse<Boolean> deleteById(@PathVariable("id") Integer id) {
        return testeeExperimentManager.deleteById(id);
    }

//    @GetMapping("/back")
//    @ApiOperation(value = "基于id获取被试实验数据信息")
//    public void testBack() {
//        sendJsonPost("http://localhost:18081/sync/syncUser","{\n" +
//                "    \"FUN_TYPE\":\"1\",\n" +
//                "    \"USER_PK_ID\":\"1234567\",\n" +
//                "    \"USER_ACCOUNT\":\"1234\",\n" +
//                "    \"USER_NAME\":\"aa\",\n" +
//                "    \"INPUT_CODE\":\"AA\",\n" +
//                "    \"USER_SEX\":\"男\",\n" +
//                "    \"USER_EMAIL\":\"123456\",\n" +
//                "    \"USER_PHONE\":\"123456\",\n" +
//                "    \"USER_POST\":\"老大\",\n" +
//                "    \"JOB_NUM\":\"001\",\n" +
//                "    \"AGENCY_PK_ID\":\"7890\",\n" +
//                "    \"STATUS\":1,\n" +
//                "    \"AGCENCY_NAME\":\"BB\",\n" +
//                "    \"AGENCY_CODE\":\"789\",\n" +
//                "    \"ROLE_LIST\":[{\"SUBJECT_CODE\":\"123456\",\"ROLE_NAME\":\"1\",\"SITE_CODE\":\"2\",\"ROLE_PK_ID\":\"3\",\"USER_PK_ID\":\"4\",\"SUBJECT_PK_ID\":\"5\",\"AGENCY_PK_ID\":\"6\",\"SITE_PK_ID\":\"7\"}]\n" +
//                "}");
//
//        log.info("回传数据！");
//    }
//
//    public static String sendJsonPost(String url, String sendData) {
//        String body = "";
//        try {
//            CloseableHttpClient client = HttpClients.createDefault();
//
//            //创建post方式请求对象
//            HttpPost httpPost = new HttpPost(url);
//
//            //装填参数
//            StringEntity s = new StringEntity(sendData, "UTF8");
//            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
//                    "application/json"));
//            //设置参数到请求对象中
//            httpPost.setEntity(s);
//            //设置header信息
//            httpPost.setHeader("Content-type", "application/json");
//            httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//
//            //执行请求操作，并拿到结果（同步阻塞）
//            HttpResponse response = client.execute(httpPost);
//            //获取结果实体
//            HttpEntity entity = response.getEntity();
//            if (entity != null) {
//                //按指定编码转换结果实体为String类型
//                body = EntityUtils.toString(entity, "UTF8");
//            }
//            EntityUtils.consume(entity);
//            //为防止频繁调用一个接口导致接口爆掉，每次调用完成后停留100毫秒
//            Thread.sleep(100);
//        } catch (Exception e) {
//            log.info("JSON数据发送失败，异常：{}", e.getMessage());
//            log.error("异常：", e);
//        }
//        return body;
//    }

    @GetMapping("/back")
    @ApiOperation(value = "基于id获取被试实验数据信息")
    public void testBack() {

       Map<String, String> map = new HashMap<>();
       map.put("json", "test");
        postMap("http://localhost:18081/research/data/backRequest",map);

        log.info("回传数据！");
    }

    @PostMapping("/backRequest")
    @ApiOperation(value = "基于id获取被试实验数据信息")
    public void testBackRequest(@RequestParam String json) {
        log.info("收到数据了！");
        log.info(json);
    }

    public static String postMap(String url, Map<String, String> contentMap) {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        List<NameValuePair> content = new ArrayList<NameValuePair>();
        //将content生成entity
        Iterator iterator = contentMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
            content.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
        }
        CloseableHttpResponse response = null;
        try {
            //循环增加header
//            Iterator headerIterator = headerMap.entrySet().iterator();
//            while (headerIterator.hasNext()) {
//                Entry<String, String> elem = (Entry<String, String>) headerIterator.next();
//                post.addHeader(elem.getKey(), elem.getValue());
//            }
            if (content.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(content, "UTF-8");
                post.setEntity(entity);
            }
            //发送请求并接收返回数据
            response = httpClient.execute(post);
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                //获取response的body部分
                HttpEntity entity = response.getEntity();
                //读取reponse的body部分并转化成字符串
                result = EntityUtils.toString(entity);
            }
            return result;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }


}
